package com.suns.client;

import com.suns.HelloServiceGrpc;
import com.suns.HelloServiceGrpc.HelloServiceStub;
import com.suns.SimpleRequest;
import com.suns.SimpleRequest.Builder;
import com.suns.SimpleResponse;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.stub.StreamObserver;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author xiangminwen
 * @date 2024/4/3 11:13
 */
public class GrpcClient1 {

    public static void main(String[] args) throws Exception {
        //创建通信管道
        ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 9000).usePlaintext().build();
        try {
            //获得代理对象Stub，使用异步监听方式处理
            HelloServiceStub serviceStub = HelloServiceGrpc.newStub(channel);
            //组装参数
            Builder request = SimpleRequest.newBuilder();
            request.setName("client").setAge(10);
            request.addCode("code1").addCode("code2");
            //返回多个
            serviceStub.hello1(request.build(), new StreamObserver<SimpleResponse>() {
                final List<SimpleResponse> list = new ArrayList<>();

                @Override
                public void onNext(SimpleResponse value) {
                    //拿到每次响应数据
                    System.out.println(value.getData());
                    list.add(value);
                }

                @Override
                public void onError(Throwable t) {
                }

                @Override
                public void onCompleted() {
                    //服务端所有响应数据后，在进行业务处理
                    System.out.println("hello1 onCompleted size=" + list.size());
                }
            });
            channel.awaitTermination(6, TimeUnit.SECONDS);
        } finally {
            if (!channel.isShutdown()) {
                channel.shutdown().awaitTermination(2, TimeUnit.SECONDS);
            }
        }
    }
}
